package com.huanledoudizhu.filter;


import cn.dev33.satoken.stp.StpUtil;
import com.huanledoudizhu.controller.result.ResultCode;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("Authorization");
        if (StpUtil.isLogin()&&(token!=null&&!token.equals(""))){
//            Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
//            String token = (String)pathVariables.get("token");
            System.out.println(token);
            if (token.equals("Bearer "+StpUtil.getTokenValue())){
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out;
        try {
            JSONObject res = new JSONObject();
            res.put("code", ResultCode.USER_NOT_LOGGED_IN.code());
            res.put("data", JSONObject.NULL);
            res.put("message", ResultCode.USER_NOT_LOGGED_IN.message());
            out = response.getWriter();
            out.append(res.toString());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
